<?php

namespace App\Http\Controllers\cms;

use App\Engine\BaseController;
use App\Engine\TokenService;
use App\Models\Image as ImageModel;
use App\Http\Validate\FileValidate;
use function app\Utils\go;
use App\Models\ImageCategory as ImageCategoryModel;
use Illuminate\Http\Request;

class Image extends BaseController
{
    private $dir='common';
    private $cid=0;
    private $sid;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->sid=TokenService::getCurrentAid();
        if(isset($this->post['cid'])){
            $this->cid=$this->post['cid'];
            $dir=ImageCategoryModel::getValueInKey('id',$this->post['cid'],'dir_name');
            if($dir)
                $this->dir=$dir;
        }

    }

    /**富文本编辑器插入图片
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function edit_img()
    {

        $this->validate($this->request,FileValidate::$rule,FileValidate::$message);

        $path=$this->request->file('img')->store("uploads/{$this->dir}");
        $data=[
            'sid'=>$this->sid,
            'url'=>$path,
            'category'=>$this->cid
        ];
        return go($data);
    }


    /**获取图片
     * @return array
     */
    public function get()
    {
        return go(ImageModel::get_image());
    }

    /**添加图片
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function insert()
    {
        $this->validate($this->request,FileValidate::$rule,FileValidate::$message);
        $path=$this->request->file('img')->store("uploads/{$this->dir}");
        $res=ImageModel::add($path,$this->cid);
        return go($res);
    }

    /**删除图片
     * @return array
     */
    public function del()
    {
        return go(ImageModel::find($this->get['id'])->delete());
    }
}
